<?php
namespace frontend\Components;
use yii\web\Application;
use yii\base\Behavior;
use common\models\User;
use common\models\VoteLog;
use common\models\Vote;

class RulesBehavior extends Behavior
{

    public function events()
    {
        return [
            Application::EVENT_BEFORE_ACTION => 'beforeAction',
        ];
    }

    public function beforeAction($event)
    {
        //验证用户是否关注
        //$this->isFocus();
        //验证用户一天只投一次
        $this->isVote();
        //验证时间
        $this->isTime();


    }


    //验证是否投过票
    static function isVote()
    {
        $log = VoteLog::find()
            ->where(['openid' => \Yii::$app->params['userinfo']['openid']])
            ->orderBy('id desc')
            ->asArray()
            ->one();
        if(date('Y-d-m', $log['created_at']) == date('Y-d-m', time())){
            \Yii::$app->params['votedate'] = true;

            //设置后台投票是否通过
            \Yii::$app->params['isvote'] = [
                'status' => '0',
                'message' => '您已经投过票了，请明天再来'
            ];
        }


        //return $log;

    }

    //验证是否关注
    static function isFocus()
    {
        $session = \Yii::$app->session;
        $res = \Yii::$app->wechat->getUserInfo($session['access_token']['openid']);

        if($res['subscribe'] !== 1){
            \Yii::$app->params['isfocus'] = '0';
            //设置后台投票是否通过
            \Yii::$app->params['isvote'] = [
                'status' => '0',
                'message' => '您未关注，请关注后再来投票!'
            ];
        }else{
            \Yii::$app->params['isfocus'] = '1';
        }
    }

    //验证开始时间
    //0 为没有开始 -1 为已结束 1为正常时间
    static function isTime()
    {
        $model = Vote::findOne(3);
        \Yii::$app->params['time_start'] = $time_start = $model->time_start;
        \Yii::$app->params['time_end'] = $time_end = $model->time_end;
        \Yii::$app->params['istime'] = '1';

        if(time() < $time_start) {
            \Yii::$app->params['istime'] = '0';
            //设置后台投票是否通过
            \Yii::$app->params['isvote'] = [
                'status' => '0',
                'message' => '投票还没开始，开始时间' . date('Y-m-d H:i:s', $time_start)
            ];
        }
        if(time() > $time_end) {
            \Yii::$app->params['istime'] = '-1';
            //设置后台投票是否通过
            \Yii::$app->params['isvote'] = [
                'status' => '0',
                'message' => '投票已经结束，开始时间' . date('Y-m-d H:i:s', $time_end)
            ];
        }

    }

}
